import { defineStore } from 'pinia';
import type { PersistenceOptions } from 'pinia-plugin-persistedstate';

interface AuthState {
  token: string;
  isLoggedIn: boolean;
  user?: {
    id: string;
    name: string;
  };
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    token: '',
    isLoggedIn: false,
    user: undefined,
  }),

  actions: {
    login(payload: { token: string; user: { id: string; name: string } }) {
      this.token = payload.token;
      this.isLoggedIn = true;
      this.user = payload.user;
    },

    logout() {
      this.token = '';
      this.isLoggedIn = false;
      this.user = undefined;
    },
  },

  persist: {
    key: 'auth-store',
    storage: localStorage,
    paths: ['token', 'user'], // 确保使用正确的类型
  } as PersistenceOptions,
});
